package JZ49_把字符串转换成整数;

public class Solution {
    public int StrToInt(String str) {
        if (str == null || "".equals(str.trim())){
            return 0;
        }
        str = str.trim();

        char[] array = str.toCharArray();
        int i = 0 ;
        int flag = 1;
        int res = 0;
        if (array[i] == '-'){
            flag = -1;
        }
        if (array[i] == '+' || array[i] == '-'){
            i++;
        }

        while (i < array.length){
            if (isNum(array[i])){
                int cur = array[i] - '0';
                res = res * 10 + cur;
                i++;
            }else {
                return 0;
            }
        }
        return res * flag;
    }

    private boolean isNum(char c) {
        return c >= '0' && c <= '9';
    }
}
